package com.example.ks.servlet;

import com.example.ks.dao.impl.UserDaoImpl;
import com.example.ks.entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        // 强制设置为普通用户角色
        int role = 0;

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        user.setRole(role);

        UserDaoImpl userDao = new UserDaoImpl();
        try {
            if (!userDao.checkUsernameExists(username) && !userDao.checkPhoneExists(phone)) {
                int userId = userDao.registerUser(user);
                if (userId != -1) {
                    // 注册成功，跳转到登录注册页面
                    response.sendRedirect("login-register.jsp");
                } else {
                    request.setAttribute("error", "注册失败，请稍后再试");
                    request.getRequestDispatcher("login-register.jsp").forward(request, response);
                }
            } else {
                request.setAttribute("error", "用户名或手机号已存在");
                request.getRequestDispatcher("login-register.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "注册失败：数据库错误");
            request.getRequestDispatcher("login-register.jsp").forward(request, response);
        }
    }
}